package com.sky.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.sky.result.Result;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.UUID;

@Data
@AllArgsConstructor
@Slf4j
public class QiniuOssUtil {
    private String accessKey;
    private String secretKey;
    private String bucket;
    private String domain;

    /**
     * 文件上传（七牛云版）
     *
     * @param bytes
     * @param objectName
     * @return
     */
    public String upload(byte[] bytes, String objectName) {
        // 构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        UploadManager uploadManager = new UploadManager(cfg);

        // 生成上传凭证，然后准备上传
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(bytes, objectName, upToken);
            // 解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            String url = domain + "/" + putRet.key;
            return url;

        } catch (QiniuException ex) {
            ex.printStackTrace();
            if (ex.response != null) {
                log.error(ex.response.toString());
                try {
                    String body = ex.response.toString();
                    log.error(body);
                } catch (Exception ignored) {
                    log.error(ignored.toString());
                }
            }
        }
        return null;
    }
}
